package com.cy.myblog.action.article;

import com.cy.myblog.action.BaseAction;
import com.cy.myblog.model.Tarticle;
import com.cy.myblog.model.Tclassify;
import com.cy.myblog.model.Tuser;
import com.cy.myblog.pageModel.Article;
import com.cy.myblog.pageModel.DataGrid;
import com.cy.myblog.pageModel.Json;
import com.cy.myblog.service.ArticleServiceI;
import com.cy.myblog.service.ClassifyServiceI;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;

/**
 * Created by Administrator on 2015/7/9.
 */
@Controller("articleAction")
@Scope("prototype")
public class ArticleAction extends BaseAction implements ModelDriven<Article> {

    private Article article = new Article();
    private ArticleServiceI articleService;
    private ClassifyServiceI classifyService;
    private File file;
    private String fileFileName;
    private String fileContentType;
    private Json json = null;
    private String url;

    /**
     * 服务端验证
     */
    public void validateAddOrUpdate() {
        if (StringUtils.isBlank(article.getTitle()) || article.getTitle().length() == 0) {
            this.addFieldError("title", "标题不能为空");
        }

        if (StringUtils.isBlank(article.getContent())) {
            this.addFieldError("container", "内容不能为空");
        }
    }

    /**
     * 添加或者更新文章
     * @return
     */
    public String addOrUpdate() {
        json = new Json();
        Tuser user = (Tuser) session.get("loginUser");
        if (user == null) {
            return LOGIN;
        }

        Tarticle dbArticle = null;
        if (StringUtils.isBlank(article.getId())) {
            dbArticle = new Tarticle();
            dbArticle.setId(UUID.randomUUID().toString());
        } else {
            dbArticle = articleService.getById(article.getId());
        }

        dbArticle.setTitle(article.getTitle());
        dbArticle.setOverview(article.getOverview());
        dbArticle.setContent(article.getContent());
        dbArticle.setReleasetime(article.getReleasetime());
        dbArticle.setTclassify(classifyService.getById(article.getClassifyid()));
        dbArticle.setTuser(user);

        //发布时间小于当前时间 直接发布 否则设置为不发布
        if (article.getReleasetime().getTime() <= new Date().getTime()) {
            dbArticle.setState(article.getState());
        } else {
            dbArticle.setState(0);
        }

        StringBuffer fileName = new StringBuffer();
        try {
            if (StringUtils.isBlank(article.getId())) {
                //图片上传
                fileName = saveImage(fileName);
            } else {
                if (StringUtils.isBlank(fileFileName)) {
                    fileName.append(dbArticle.getFilename());
                } else {
                    fileName = saveImage(fileName);
                }
            }
        } catch (IOException e) {
            json.setMsg("上传文件出错了!");
            json.setRedirectPage("/jsp/backend/article/edit_article.jsp");
            return MESSAGE;
        }

        json.setMsg("发布成功");
        json.setFun("'" + article.getTabTitle() + "'");
        dbArticle.setFilename(StringUtils.isNotBlank(fileName) ? fileName.toString() : "");
        articleService.save(dbArticle);
        return MESSAGE;
    }


    /**
     * 上传图片
     * @param fileName
     * @return
     * @throws IOException
     */
    public StringBuffer saveImage(StringBuffer fileName) throws IOException {
        if (fileFileName != null) {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/upload");
            fileName = fileName.append(new Date().getTime()).append(fileFileName.substring(fileFileName.indexOf(".")));

            File rootFile = new File(rootPath);
            if (!rootFile.exists())
                rootFile.mkdir();

            InputStream is = new FileInputStream(file);
            OutputStream os = new FileOutputStream(new File(rootFile, fileName.toString()));
            byte[] buffer = new byte[1024];
            int length = 0;

            while ((length = is.read(buffer)) != -1) {
                os.write(buffer);
            }

            os.close();
            is.close();
        }

        return fileName;
    }

    public String loadClassify() {
        List<Tclassify> datas = classifyService.findAll();

        for (Tclassify data : datas)
            article.getClassifys().put(data.getId() + "", data.getClassifyname());

        return TOJSON;
    }

    public void insertClassify() {
        json = new Json();
        if (StringUtils.isNotEmpty(article.getClassifyname())) {
            Tclassify classify = new Tclassify();
            Map<String, String> data = new HashMap<String, String>();
            try {
                classify.setClassifyname(article.getClassifyname());
                classify.setState(1);
                classifyService.save(classify);
                String id = classifyService.getByName(classify.getClassifyname()).getId() + "";
                data.put("id", id);
                data.put("name", classify.getClassifyname());
                json.setObj(data);
                json.setSuccess(true);
                writeJson(json);
            } catch (Exception e) {
                json.setMsg("数据异常,请重新输入");
                json.setSuccess(false);
                writeJson(json);
            }
        } else {
            json.setMsg("分类名称不能为空!");
            json.setSuccess(false);
            writeJson(json);
        }
    }

    /**
     * 转发到修改页面
     */
    public String toEditArticle() {
        try {
            Tarticle tar = articleService.getById(article.getId());
            BeanUtils.copyProperties(tar, article);
            article.setClassifyid(tar.getTclassify().getId());
            url = "/jsp/backend/article/edit_article.jsp";
        } catch (BeansException e) {
            e.printStackTrace();
        }

        return SUCCESS;
    }

    public void loadArticle() {
        try {
            DataGrid dataGrid = articleService.findByPage(article);
            super.writeJson(dataGrid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void remove() {
        json = new Json();
        try {
            articleService.delete(article);
            json.setSuccess(true);
            json.setMsg("删除成功!");
        } catch (Exception e) {
            json.setSuccess(false);
            json.setMsg("删除失败!");
            e.printStackTrace();
        } finally {
            super.writeJson(json);
        }
    }

    /**
     * 操作置顶
     */
    public void top() {
        json = new Json();
        try {
            articleService.toTop(article);
            json.setSuccess(true);
            json.setMsg("操作成功!");
        } catch (Exception e) {
            json.setSuccess(true);
            json.setMsg("操作失败!");
            e.printStackTrace();
        } finally {
            super.writeJson(json);
        }
    }

    @Override
    public Article getModel() {
        return article;
    }

    public void setArticle(Article article) {
        this.article = article;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public Json getJson() {
        return json;
    }

    public void setJson(Json json) {
        this.json = json;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Resource(name = "articleService")
    public void setArticleService(ArticleServiceI articleService) {
        this.articleService = articleService;
    }

    @Resource(name = "classifySerivce")
    public void setClassifyService(ClassifyServiceI classifyService) {
        this.classifyService = classifyService;
    }

}